/**
 * ChatHook.java 2008-05-14
 * 
 * Linker is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

package linker.chat;

import java.util.ArrayList;

import org.jivesoftware.smack.packet.Message;

import linker.plugin.Plugin;

/**
 * Chat hook,it can pass messages to send or recieved to plugins.
 * 
 * @version 2008-05-14
 * @author Jianfeng tujf.cn@gmail.com
 * 
 */

public final class PluginChat {
	/**
	 * The pluginChatListener's list.
	 */
	private static ArrayList<PluginChatListener> list;

	/**
	 * The default constructor.
	 */
	private PluginChat() {
	}

	/**
	 * 
	 * @param plugin
	 *            The Plugin use the listener.
	 * @param s
	 *            The buddy that the plugin used to listen.
	 * 
	 */
	public static void addChatListener(final Plugin plugin, final String s) {
		if (list == null) {
			list = new ArrayList<PluginChatListener>();
		}

		list.add(new PluginChatListener(plugin, s));
	}

	/**
	 * Pass the recieved chat massage to the listening puglin.
	 * 
	 * @param message
	 *            The recieved message.
	 * @return The message to be displayed in chatWindow.
	 */
	public static String passChatMessage(final Message message) {

		if (list == null) {
			return null;
		}

		StringBuffer buffer = null;

		for (PluginChatListener listener : list) {
			Plugin plugin = listener.getPlugin();
			String buddy = listener.getBuddy();

			if (message.getTo().indexOf(buddy) < 0
					&& message.getFrom().indexOf(buddy) < 0) {
				continue;
			}

			String temp = null;
			temp = plugin.recieveChatMessage(message);
			if (temp != null) {
				buffer.append(temp);
			}
		}

		if (buffer == null) {
			return null;
		}

		return buffer.toString();
	}

	/**
	 * Remove the chatListener by the given PuginItem and the buddy.
	 * 
	 * @param item
	 *            The pluginItem
	 * @param s
	 *            The buddy.
	 */
	public static void removeChatListener(final Plugin item, final String s) {
		if (list == null) {
			return;
		}

		for (PluginChatListener listener : list) {
			if (item != listener.getPlugin()) {
				continue;
			}

			if (listener.getBuddy().indexOf(s) >= 0) {
				list.remove(listener);
				return;
			}
		}
	}

}
